package com.itheima.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    //根据手机号查询会员
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //新增会员
    public void add(Member member) throws Exception{
        if(member.getPassword() != null){
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        Date today = DateUtils.getToday();
        member.setRegTime(today);
        memberDao.add(member);
    }

    //根据月份统计会员数量
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();
        for(String m : month){
            m = m + ".31";//格式：2019.04.31
            Integer count = memberDao.findMemberCountBeforeDate(m);
            list.add(count);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> findAgeDistribution() {
        return memberDao.findAgeDistribution();
    }

    //根据多选框选择项查询数据
    public List<Member> getBusinessReport(Integer[] ids) {
      /*  List<Map> list = new ArrayList<Map>();
        Map<String,Object> result = new HashMap<>();
            for (Integer id : ids) {
                List<String> setmeal = memberDao.findMemberDataSetmeal(id);
                memberDao

                result.put("setmeal",setmeal);
            }*/

        List<Member> members = new ArrayList<>();
        for (Integer id : ids) {
            Member member = memberDao.findMemberById(id);
            members.add(member);
            List<Order> orders = memberDao.findOrderByMemberId(id);
            member.setOrders(orders);
        }

        return members;
    }

    public void deleteById(Integer id) {
        //判断会员编号是否在t_order数据库表中有关联，如果有关联不能删除，没有关联可以删除。
        long count = memberDao.findCountByMemberId(id);
        if (count > 0) {
            //t_order表格里面可以查询到member则不能删除，抛出一个异常
            new RuntimeException();
        }
        memberDao.deleteById(id);
    }

    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    //分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String,Object>> page = memberDao.selectByCondition(queryString);
        for (Map<String ,Object> map:  page) {
            Date birthday = (Date) map.get("birthday");
            String birthdayStr = DateUtils.parseDate2String(birthday);
            Date date = new Date();
            String today = DateUtils.parseDate2String(date);
            //学业期限 = 毕业时间 - 入学时间
            if(StringUtils.isNotEmpty(birthdayStr) ){//毕业时间 与 入学时间均不为空时
                int enrolmentTimes = Integer.parseInt(birthdayStr.substring(0,4));//截取前四位字段转化为整型（就是取了年份）
                int graduationTimes = Integer.parseInt(today.substring(0,4));
                map.put("age",String.valueOf(graduationTimes-enrolmentTimes));
            }
            Date regTime = (Date) map.get("regTime");
            String regTimestr = DateUtils.parseDate2String(regTime, "yyyy-MM-dd");
            map.put("regTime",regTimestr);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

}
